

var jwt = require("jsonwebtoken");

const secret = "WH2105-daydayup"


exports.createToken = function (data) {
    return jwt.sign(data, secret, { expiresIn: '2h' })   // expiresIn 有效时间2小时 
}


var decodeToken = function (token) {
    return new Promise(function (resolve, reject) {
        jwt.verify(token, secret, (err, data) => {
            if (err) {
                reject(err)
                console.log(err)
            } else {
                resolve(data)
            }
        })
    })
}

exports.decodeToken = decodeToken;



exports.checkToken = function (req, res, callback) {
    var token = req.headers.token;
    if (token) {
        decodeToken(token)
            .then(data => {
                callback(data)
            })
            .catch(err => {
                res.json({
                    code: 3000,
                    msg: "token无效或者过期失效,请重新登录",
                    type: 0
                })
            })
    } else {
        res.json({
            code: 3000,
            msg: "token不存在,请重新登录",
            type: 0
        })
    }
}